package com.zhouyer.edu.utils;

import com.zhouyer.edu.annotation.MyService;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 获取连接工具，一个线程一个Connection连接对象
 *
 * @author zhouyer
 */
@MyService
public class ConnectionUtils {
    /**
     * 存储当前线程的连接
     */
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 获取当前线程的连接
     *
     * @return
     * @throws SQLException
     */
    public Connection getCurrentThreadConnection() throws SQLException {
        /**
         * 首先判断当前线程是否已经绑定了Connection，如果没有绑定，那么从连接池中获取连接并绑定到当前线程
         */
        Connection connection = threadLocal.get();
        if (null == connection) {
            // 从连接池中获取连接
            connection = DruidUtils.getInstance().getConnection();
            // 将连接与当前线程绑定
            threadLocal.set(connection);
        }
        return connection;
    }
}
